

Vue.createApp({
    // 定义组件
    components:{
        "my-article": ARTICLE,
        "left-nav": LEFT_NAV
    },
    // 初始化
    setup(){
        // reactive定义变量运行存储
        // toRefs将数据返回
        const {
            reactive, toRefs
        } = Vue
        // 定义变量，即所需数据
        const state = reactive({
            type: [
                {name: "文章", type: "article"},
                {name: "用户", type: "user"},
                {name: "分类", type: "classify"},
            ],
            articles: [],
            classify: [],
            users: []
        })
        let that = state
        // 初始化，加载文章内容
        search(that, 0)
        // 左侧导航栏的切换以及数据请求
        $(function () {
            let items = $("#search .leftNav li")
            items.each(function (index) {
                $(this).click(function () {
                    search(that, index)
                    items.each(function () {
                        $(this).removeClass("active")
                    })
                    $(this).addClass("active")
                    // 结果列表的隐藏与显示
                    let results = $("#search #result>div")
                    results.each(function () {
                        $(this).hide()
                    })
                    results.eq(index).show()
                })
            })
        })
        // 返回数据
        return {
            ...toRefs(state)
        }
    },
    updated:function(){
        let that = this
        $(function() {
            // 用html替换个人简介
            let userEles = $("#search .user li .profile")
            if (that.users != null) {
                that.users.forEach((element, index) => {
                    if (element.profile.trim().length == 0) {
                        element.profile = "谢谢你的来访~"
                    }
                    userEles.eq(index).html(element.profile)
                });
            }
            // 用html替换专题简介
            let classifyEles = $("#search .classify li .desc")
            if (that.classify != null) {
                that.classify.forEach((element, index) => {
                    classifyEles.eq(index).html(element.description)
                });
            }
        })
    }
    // 绑定app
}).mount("#search")


function search(that, index) {
    let type = that.type[index].type
    let searchBtn = $("#head #searchInput")
    let content = searchBtn.val()
    if ("" == content.trim()) {
        swalError("搜索失败", "搜索内容不能为空")
        return
    }
    get("/search/" + content + "/" + type, function (data) {
        console.log(data);
        if (index == 0) {
            that.articles = data
        } else if (index == 1) {
            that.users = data
        } else if (index == 2) {
            that.classify = data
        } else {
            console.log("类型有误");
        }
    })
}
